﻿using NDF.Web.Optimization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Optimization;

namespace System.Web.Optimization
{
    public static class NDFBundles
    {
        public static IHtmlString Render(object key)
        {
            return RenderFormat(null, key);
        }

        public static IHtmlString RenderFormat(string tagFormat, object key)
        {
            if (key == null) 
            {
                throw new ArgumentNullException("key");
            }
            List<IHtmlString> list = new List<IHtmlString>();
            var hasKey = BundleWrapperFactory.HasKey(key);
            if (hasKey)
            {
                var array = BundleWrapperFactory.GetBundleWrapperList(key);
                foreach (var item in array)
                {
                    if (item.Bundle is ScriptBundle) 
                    {
                        list.Add(string.IsNullOrWhiteSpace(tagFormat) ? Scripts.Render(item.VirtualPath) : Scripts.RenderFormat(tagFormat, item.VirtualPath));
                    }
                    else if (item.Bundle is StyleBundle) 
                    {
                        list.Add(string.IsNullOrWhiteSpace(tagFormat) ? Styles.Render(item.VirtualPath) : Styles.RenderFormat(tagFormat, item.VirtualPath));
                    }
                }
            }
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var item in list)
            {
                stringBuilder.AppendLine(item.ToHtmlString());
            }
            return new HtmlString(stringBuilder.ToString());
        }


        public static IHtmlString RenderPath(params string[] paths)
        {
            throw new NotImplementedException();
        }


        public static IHtmlString Url(string virtualPath)
        {
            var type = BundleUtils.GetBundleType(virtualPath);
            if (type == BundleType.JavaScript)
            {
                return Scripts.Url(virtualPath);
            }
            else
            {
                return Styles.Url(virtualPath);
            }
        }

    }
}
